#include "AddUserInfo.h"
#include "db/DBManager.h"

#include <QJsonObject>
#include <QSqlQuery>
#include <QSqlError>
#include <QDebug>

/*

@app.route('/addUserInfo')
def addUserInfo():
    global g_dict_mobile_code
    phone = request.args.get('phone')
    openid = request.args.get('openid')
    cs = request.args.get('cs')


    if not phone in g_dict_mobile_code:
        return json.dumps({"code":1, "msg":'ng'})


    mix = g_dict_mobile_code[phone]+phone

    print("cs: ", cs)
    print("mix: ", mix)


    if cs == mix:
    # if cs == m5.hexdigest():
        info = {}
        info['phone'] = phone
        info['openid'] = openid

        addUserInfoToDb(info)

        # add to db
        # remove the used mobile when reg ok
        g_dict_mobile_code.pop(phone)

        return json.dumps({"code":0, "msg":'ok'})
    else:
        return json.dumps({"code":1, "msg":'ng'})

*/

void AddUserInfo::handleSession()
{

    QMap<QString, QString> mapQuery = m_session->requestUrlQuery();
    QString strPhone = mapQuery.value("phone");
    QString strOpenId = mapQuery.value("openid");
    QString strCs = mapQuery.value("cs");

    if (!s_mapPhoneRandom.contains(strPhone))
    {
        QJsonObject obj;
        obj.insert("code", 1);
        obj.insert("msg", "ng");
        m_session->replyJsonObject(obj);
        return;
    }

    // if has the phone, remove the phone after process
    QString strRandom = s_mapPhoneRandom.value(strPhone);
    s_mapPhoneRandom.remove(strPhone);

    QString strMix = strRandom+strPhone;
    if (strCs == strMix)
    {
        qDebug() << "strCs == strMix";

        QSqlDatabase db = DBManager::database("core_config");

        QString strSql = QString("insert into user_info(szPhone, szOpenid) values('%1', '%2')").arg(strPhone).arg(strOpenId);


        QSqlQuery query(db);

        if(!query.exec(strSql))
        {
            qDebug()<<"exec insert user_info error, "<<query.lastError().text();
            return;
        }

        QJsonObject obj;
        obj.insert("code", 0);
        obj.insert("msg", "ok");
        m_session->replyJsonObject(obj);
    }
    else
    {
        qDebug() << "strCs != strMix";

        QJsonObject obj;
        obj.insert("code", 1);
        obj.insert("msg", "ng");
        m_session->replyJsonObject(obj);
    }
}



